package service

import (
	"consul_grpc/config"
	"consul_grpc/discover"
	"encoding/json"
	"errors"
	"fmt"
)

var ErrNotServiceInstances = errors.New("instances are not existed")

//具体GRPC服务的逻辑实现方法接口
type Service interface {
	HealthCheck() bool
	Greet(string) string
	Discovery(string) (string, error)
}

//定义接口实现结构体，并且有个服务发现接口属性，用于调用服务发现方法
type ServiceImpl struct {
	discoverClient discover.DiscoveryClient
}

//初始化
func NewServiceImpl(client discover.DiscoveryClient) Service {
	return &ServiceImpl{
		discoverClient: client,
	}
}

//以下是简单的处理逻辑
func (srv *ServiceImpl) HealthCheck() bool {
	return true
}

func (srv *ServiceImpl) Greet(name string) string {
	return fmt.Sprintf("hello %s, Happy Day!", name)
}

func (srv *ServiceImpl) Discovery(serviceName string) (string, error) {
	instance := srv.discoverClient.DiscoverServices(serviceName, config.Logger)
	if instance == nil || len(instance) == 0 {
		return "Don't have instances", ErrNotServiceInstances
	}
	res, _ := json.Marshal(instance)
	return string(res), nil
}

//自定义类型
type ServiceMiddleware func(Service) Service
